package main

import (
	"context"
	"gitee.com/trackertrader/rpcx/log"
	rpcxserver "gitee.com/trackertrader/rpcx/server"
	"gitee.com/trackertrader/trackersdk/api"
	"github.com/urfave/cli/v2"
	"net"
	"os"
	"os/signal"
	"syscall"
)

// QuoteRPC服务
type QuoteRPC struct{}

var sigCh = make(chan os.Signal, 2)
var shutdownCh = make(chan struct{})
var shutdownDone = make(chan struct{})
var RpcServer *rpcxserver.Server

/**
 * @Description: 行情RPC服务
 * @param cctx
 * @return error
 */
func serveRPC(cctx *cli.Context) error {
	RpcServer = rpcxserver.NewServer()
	RpcServer.Plugins.Add(&ConnectionPlugin{})
	_ = RpcServer.Register(new(QuoteRPC), "")
	addr := Conf.Host
	signal.Notify(sigCh, syscall.SIGTERM, syscall.SIGINT)
	go func() {
		select {
		case sig := <-sigCh:
			log.Info("received signal", "signal", sig)
		case <-shutdownCh:
			log.Info("received shutdown", "signal")
		}

		// graceful shutting down
		_ = RpcServer.Shutdown(cctx.Context)
		log.Info("quoterecorder stoped")

		close(shutdownDone)
	}()

	err := RpcServer.Serve("tcp", addr)
	if err != nil {
		log.Info("quoterecorder rpc server: ", err)
	}
	return nil
}

/**
 * @Description: TCP连接状态插件
 */
type ConnectionPlugin struct {
}

/**
 * @Description: TCP连接事件
 * @receiver p
 * @param conn
 * @return net.Conn
 * @return bool
 */
func (p *ConnectionPlugin) HandleConnAccept(conn net.Conn) (net.Conn, bool) {
	return conn, true
}

/**
 * @Description: TCP断开事件
 * @receiver p
 * @param conn
 * @return bool
 */
func (p *ConnectionPlugin) HandleConnClose(conn net.Conn) bool {
	return true
}

/**
 * @Description: 终止QuantServer
 * @receiver d
 * @param ctx
 * @param args
 * @param reply
 * @return error
 */
func (d *QuoteRPC) StopQuantServer(ctx context.Context, args api.Args, reply *api.Reply) error {
	shutdownCh <- struct{}{}
	reply.Code = 0
	return nil
}

/**
 * @Description: 拨通行情通道
 * @receiver d
 * @param ctx
 * @param args
 * @param reply
 * @return error
 */
func (d *QuoteRPC) Dial(ctx context.Context, args api.Args, reply *api.Reply) error {
	return nil
}
